import { useCallback, useState, useEffect } from "react";
import { getTree } from "./api";
export default () => {
  const [items, setItems] = useState<any[]>();

  const getAuthMenuList = useCallback((items: any[]) => {
    let list = [];
    for (let i = 0; i < items.length; i++) {
      const item = items?.[i];
      const newItem = {
        value: item?.id,
        title: item?.name,
      };

      if (item?.children?.length) {
        newItem.children = getAuthMenuList(item?.children);
      }
      list.push(newItem);
    }
    return list;
  }, []);
  const getTreeData = useCallback(async () => {
    const res = await getTree();
    const { code, data } = res;
    if (code === 0 && data?.length) {
      const menuList = getAuthMenuList(data);
      setItems([...menuList]);
    }
  }, []);

  useEffect(() => {
    getTreeData();
  }, [getTreeData]);

  return [items];
};
